<?php

$userid = get_loggedin_userid();
$from = get_input('from');
$to = get_input('to');
$count = get_input('count');
$client_id = get_input('client_id');
$apps = get_input('apps');

if ($apps) {
    $apps = json_decode($apps, TRUE);
}

if(!$count) {
    $count = 10;
}

// Get variables
$keywords = get_input('keywords');
$keywords = get_array_from_keywords($keywords);
if(count($keywords) < 2 && $keywords[0] == '') {
    die(export_result(400, 'empty keyword'));
}
$like_username = build_like_query('ue.username', $keywords);
$like_name = build_like_query('ue.name', $keywords);
$like_email = build_like_query('ue.email', $keywords);
$userEntity = get_entity($userid);
$username = $userEntity->username;

global $CONFIG;
$params['query'] = $keywords;
$query = sanitise_string($keywords);

$join = "JOIN {$CONFIG->dbprefix}users_entity ue ON e.guid = ue.guid";
$params['joins'] = array($join);

$where = "
(
(ue.guid = e.guid) 
AND (
    $like_username
    OR $like_name
    OR $like_email
    )
AND (ue.username <> '$username')
)";

if ($from != NULL) {
    $where .= " AND (ue.guid < $from) ";
}

//$fields = array('username', 'name');
//$where = search_get_where_sql('ue', $fields, $params, FALSE);

$params['wheres'] = array($where);

// override subtype -- All users should be returned regardless of subtype.
$params['subtype'] = ELGG_ENTITIES_ANY_VALUE;

if (is_array($apps)) {
    $params['limit'] = $count;
} else {
    $params['limit'] = $count;
}

$params['count'] = FALSE;
$params['order_by'] = 'e.guid desc';
$entities = elgg_get_entities($params);

$results = array();

// add the volatile data for why these entities have been returned.
foreach ($entities as $entity) {
    
    
    if (is_array($apps)) {
        // Filter
        if(count($results) < $count) {
            
            $ok = FALSE;
            foreach($apps as $app) {
                if($entity->getMetadata($app)) {
                    $ok = TRUE;
                    
                    break;
                } else {
                    
                }
            }
            if(!$ok) {
                continue;
            }
            
        
        } else {
            break;
        }
    } else {
        // Do nothing
    }
    

    $username = search_get_highlighted_relevant_substrings($entity->username, $query);
    $entity->setVolatileData('search_matched_title', $username);

    $name = search_get_highlighted_relevant_substrings($entity->name, $query);
    $entity->setVolatileData('search_matched_description', $name);
    $userid = $entity->getGUID();
    $result = userToArray($entity, $client_id, FALSE);



    array_push($results, $result);
}

// Find Facebook, Gowalla, Foursquare
echo json_encode(export_result(200, $results));
?>